package org.destinyshine.cricket.mavenplugin;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.destinyshine.cricket.connector.Connector;
import org.destinyshine.cricket.container.WebApplicationContainer;
import org.destinyshine.cricket.server.CricketServer;
import org.destinyshine.cricket.server.LifecycleException;

import java.io.File;
import java.io.IOException;

/**
 * to start cricket server.
 *
 * @goal start
 * @requiresDependencyResolution test
 * @execute phase="test-compile"
 */
public class CricketStartMojo extends AbstractMojo {

    /**
     * @parameter expression="${cricket.port}" default-value="8080"
     */
    private int port;

    public void execute() throws MojoExecutionException {
        getLog().info("configuration port=" + port);

        MavenProject project = (MavenProject) getPluginContext().get("project");
        //getLog().info("context:" + project.get);
        getLog().info("dir:" + new File("").getAbsolutePath());
        String webappDir = ("target/" + project.getArtifactId() + "-" + project.getVersion());
        CricketServer server = new CricketServer();
        WebApplicationContainer container = new WebApplicationContainer();
        container.createContext("/", webappDir);
        server.setWebApplicationContainer(container);

        Connector connector = server.createConnector("tcp:127.0.0.1:" + port);
        try {
            connector.connect();
        } catch (IOException e) {
            throw new MojoExecutionException("connect exception.", e);
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            getLog().error("Main Thread :InterruptedException", e);
        }

        try {
            server.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }
    }
}
